package org.jeecg.modules.monitoring.j_monitoring.job.history;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.monitoring.j_monitoring.entity.ScreenData;
import org.jeecg.modules.monitoring.j_monitoring.entity.SyncResult;
import org.jeecg.modules.monitoring.j_monitoring.service.IScreenDataService;
import org.jeecg.modules.monitoring.j_monitoring.service.impl.ScreenDataServiceImpl;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 同步大屏数据
 */
@Slf4j
public class SyncScreenData implements Job {

    @Autowired
    private ScreenDataServiceImpl logService;

    private SyncResult getList(){
        SyncResult syncResult = new SyncResult();
        DynamicDataSourceContextHolder.push("history");
        try{
            syncResult.setStatus(true);
            QueryWrapper<ScreenData> logQueryWrapper = new QueryWrapper();
            syncResult.setList(logService.list(logQueryWrapper));
        }catch (Exception e){
            e.printStackTrace();
            syncResult.setStatus(false);
        } finally {
            DynamicDataSourceContextHolder.clear();
        }
        return syncResult;
    }

    private void removeAll(){
        QueryWrapper<ScreenData> logQueryWrapper = new QueryWrapper();
        logService.remove(logQueryWrapper);
    }

    /***
     * 执行
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        log.info(String.format("同步动环日志数据,时间:" + DateUtils.getTimestamp()));

        SyncResult result = this.getList();
        if (result.getStatus()){

            this.removeAll();
            logService.saveBatch(result.getList());

        }

    }


}
